package org.lds.hotkey.console.business.worker.service.impl;

import org.apache.commons.lang3.BooleanUtils;
import org.lds.hotkey.common.model.dto.ResultDTO;
import org.lds.hotkey.common.util.AssertUtil;
import org.lds.hotkey.console.business.app.entity.App;
import org.lds.hotkey.console.business.app.model.request.AppBaseGetByKeyRequest;
import org.lds.hotkey.console.business.app.service.AppBaseService;
import org.lds.hotkey.console.business.worker.entity.Worker;
import org.lds.hotkey.console.business.worker.model.request.WorkerBaseCreateRequest;
import org.lds.hotkey.console.business.worker.model.request.WorkerBaseGetByKeyRequest;
import org.lds.hotkey.console.business.worker.model.request.WorkerBaseUpdateRequest;
import org.lds.hotkey.console.business.worker.service.WorkerBaseService;
import org.lds.hotkey.console.business.worker.service.WorkerRemoteService;
import org.lds.hotkey.console.common.enums.ConsoleErrorEnum;
import org.lds.hotkey.console.remote.model.request.WorkerRegisterRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class WorkerRemoteServiceImpl implements WorkerRemoteService {
    @Autowired
    private AppBaseService appBaseService;

    @Autowired
    private WorkerBaseService workerBaseService;

    @Override
    public ResultDTO<Long> registerWorker(WorkerRegisterRequest request) {
        Long appId = getAppId(request.getAppName());
        AssertUtil.assertTrue(Objects.nonNull(appId), ConsoleErrorEnum.APP_NAME_NOT_EXIST);

        request.setAppId(appId);
        saveWorkerIfNeed(request);
        return ResultDTO.success(appId);
    }

    private Long getAppId(String appName) {
        App app = appBaseService.getAppByKey(AppBaseGetByKeyRequest.builder().name(appName).build());
        if (Objects.isNull(app)) return null;
        return app.getId();
    }

    private void saveWorkerIfNeed(WorkerRegisterRequest request) {
        Worker worker = workerBaseService.getWorkerByKey(WorkerBaseGetByKeyRequest.builder()
                .appId(request.getAppId())
                .name(request.getName())
                .build());
        if (Objects.nonNull(worker)) {
            // 自动上线
            if (BooleanUtils.isFalse(worker.getEnable())) {
                workerBaseService.updateWorker(WorkerBaseUpdateRequest.builder().id(worker.getId()).enable(true).build());
            }
            return;
        }

        workerBaseService.createWorker(WorkerBaseCreateRequest.builder()
                .appId(request.getAppId())
                .name(request.getName())
                .ip(request.getIp())
                .port(request.getPort())
                .build());
    }
}
